package com.guaoran.solr;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 
 * @author alex.lu
 * 
 */

public class MyHttpClient {
	final private static Log logger = LogFactory.getLog(MyHttpClient.class);
	private static MultiThreadedHttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
	private static int connectionTimeOut = 10000;  
	private static int databaseTimeOut = 2;
	private static int socketTimeOut = 30000;
	private static int maxConnectionPerHost = 5;
	private static int maxTotalConnections = 2;
	// 标志初始化是否完成的flag
	private static boolean initialed = false;

	// 初始化ConnectionManger的方法
	public static void SetPara() {
		manager.getParams().setConnectionTimeout(connectionTimeOut);   //设置连接超时数，单位：毫秒
		manager.getParams().setSoTimeout(socketTimeOut);            //设置请求超时数，单位：毫秒
		manager.getParams().setDefaultMaxConnectionsPerHost(
				maxConnectionPerHost);
		manager.getParams().setMaxTotalConnections(maxTotalConnections);
		initialed = true;
	}

	// 通过get方法获取网页内容
	public static String getGetResponseWithHttpClient(String url, String encode) {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		GetMethod get = new GetMethod(url);
		get.setFollowRedirects(true);
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeOut); 
			client.getHttpConnectionManager().getParams().setMaxTotalConnections(maxTotalConnections);
			client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
			client.getHttpConnectionManager().getParams().setSoTimeout(socketTimeOut);
			
			int status = client.executeMethod(get);  //返回响应码，200为成功
			
			// 在目标页面情况未知的条件下，不推荐使用getResponseBodyAsString()方法
			// String strGetResponseBody = post.getResponseBodyAsString();
			BufferedReader in = new BufferedReader(new InputStreamReader(get
					.getResponseBodyAsStream(), get.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			result = resultBuffer.toString();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					get.getResponseCharSet(), encode);
		} catch (Exception e) {
			 //e.printStackTrace();
			logger.debug("Connection url: "+url+" Fail.."+e.toString());
			result = "";
		} finally {
			get.releaseConnection();
		}
		return result;
	}

	/**
	 *  通过get方法获取网页内容，增加设置连接超时数，和请求超时数
	 * @param url
	 * @param encode
	 * @param connectionTimeOut 设置连接超时数：单位毫秒
	 * @param socketTimeOut  请求超时数：单位毫秒
	 * @return
	 */
	public static String getGetResponseWithHttpClient(String url, String encode,int connectionTimeOut,int socketTimeOut) {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		GetMethod get = new GetMethod(url);
		get.setFollowRedirects(true);
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeOut); 
			client.getHttpConnectionManager().getParams().setMaxTotalConnections(maxTotalConnections);
			client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(maxConnectionPerHost);
			client.getHttpConnectionManager().getParams().setSoTimeout(socketTimeOut);
			
			int status = client.executeMethod(get);  //返回响应码，200为成功
			
			// 在目标页面情况未知的条件下，不推荐使用getResponseBodyAsString()方法
			// String strGetResponseBody = post.getResponseBodyAsString();
			BufferedReader in = new BufferedReader(new InputStreamReader(get
					.getResponseBodyAsStream(), get.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			result = resultBuffer.toString();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					get.getResponseCharSet(), encode);
		} catch (Exception e) {
			 //e.printStackTrace();
			logger.debug("Connection url: "+url+" Fail.."+e.toString());
			result = "";
		} finally {
			get.releaseConnection();
		}
		return result;
	}

	public static String getPostResponseWithHttpClient(String url, String encode) {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		PostMethod post = new PostMethod(url);
		post.setFollowRedirects(false);
		StringBuffer resultBuffer = new StringBuffer();
		String result = null;
		try {
			int status = client.executeMethod(post); //返回响应码，200为成功
			BufferedReader in = new BufferedReader(new InputStreamReader(post
					.getResponseBodyAsStream(), post.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					post.getResponseCharSet(), encode);
		} catch (Exception e) {
			// e.printStackTrace();
			result = "";
		} finally {
			post.releaseConnection();
		}
		return result;
	}

	public static String getPostResponseWithHttpClient(String url,
			String encode, NameValuePair[] nameValuePair) {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, encode);
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,encode);
        

        InputStream is = null;

		post.setRequestBody(nameValuePair);
		post.setFollowRedirects(false);
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			client.executeMethod(post);
			BufferedReader in = new BufferedReader(new InputStreamReader(post
					.getResponseBodyAsStream(), post.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					post.getResponseCharSet(), encode);
		} catch (Exception e) {
			// e.printStackTrace();
			result = "";
		} finally {
			post.releaseConnection();
		}
		return result;
	}
	
	/**
	 * 
	 * <p>Description: http+xml request 按流发送 </p>
	 * @param url
	 * @param encode
	 * @param requestBody  请求的xml内容
	 * @throws Exception
	 * @return String  
	 * @exception
	 */
	public static String getPostResponseWithHttpClient(String url,
			String encode, String requestBody) throws Exception {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "utf-8");
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        

        ByteArrayRequestEntity entity = new ByteArrayRequestEntity(requestBody.getBytes("utf-8"));
        
        InputStream is = null;

		post.setRequestEntity(entity);
		post.setFollowRedirects(false);
		
		post.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
		//	System.out.println("发送XML文件请求长度：===========："+String.valueOf(entity.getContentLength()));
		post.setRequestHeader("Content-Length", String.valueOf(entity.getContentLength()));
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			client.executeMethod(post);
			BufferedReader in = new BufferedReader(new InputStreamReader(post
					.getResponseBodyAsStream(), post.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					post.getResponseCharSet(), encode);
		} catch (Exception e) {
			// e.printStackTrace();
			result = "";
		} finally {
			post.releaseConnection();
		}
		return result;
	}
	
	/**
	 * 
	 * <p>Description: http+json request 按流发送 </p>
	 * @param url
	 * @param encode
	 * @param requestBody  请求的json内容
	 * @throws Exception
	 * @return String  
	 * @exception
	 */
	public static String getPostResponseWithHttpClientJson(String url,
			String encode, String requestBody) throws Exception {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "utf-8");
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        

        ByteArrayRequestEntity entity = new ByteArrayRequestEntity(requestBody.getBytes("utf-8"));
        
        InputStream is = null;

		post.setRequestEntity(entity);
		post.setFollowRedirects(false);
		
		post.setRequestHeader("Content-Type", "application/json;charset=utf-8");
		//	System.out.println("发送XML文件请求长度：===========："+String.valueOf(entity.getContentLength()));
		post.setRequestHeader("Content-Length", String.valueOf(entity.getContentLength()));
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			int status = client.executeMethod(post);
			BufferedReader in = new BufferedReader(new InputStreamReader(post
					.getResponseBodyAsStream(), post.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					post.getResponseCharSet(), encode);
		} catch (Exception e) {
			// e.printStackTrace();
			result = "";
		} finally {
			post.releaseConnection();
		}
		return result;
	}
	
	public static String getPostResponseWithHttpClient(String url,
			String encode, Map<String, Object> map) throws Exception {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "utf-8");
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        
        
        Map<String, String> httpParams = (Map<String, String>)map.get("httpParams");
        Set<String> keySet = httpParams.keySet();
        List<Part> partList = new ArrayList<Part>();
        for(String key : keySet){
        	partList.add(new StringPart(key, httpParams.get(key)));
        }
        partList.add(new CustomFilePart("fileName",new File("F:/qiupengtest.jpg")));
        Part[] parts = partList.toArray(new Part[]{});
        
        MultipartRequestEntity entity = new MultipartRequestEntity(parts,post.getParams());
        
        InputStream is = null;

		post.setRequestEntity(entity);
		post.setFollowRedirects(false);
		
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			client.executeMethod(post);
			BufferedReader in = new BufferedReader(new InputStreamReader(post
					.getResponseBodyAsStream(), post.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					post.getResponseCharSet(), encode);
		} catch (Exception e) {
			// e.printStackTrace();
			result = "";
		} finally {
			post.releaseConnection();
		}
		return result;
	}
	
	
	
	private static String ConverterStringCode(String source, String srcEncode,
			String destEncode) {
		if (source != null) {
			try {
				return new String(source.getBytes(srcEncode), destEncode);
			} catch (UnsupportedEncodingException e) {
				// e.printStackTrace();
				return "";
			}
		} else {
			return "";
		}
	}

	public static String checkConnetion(String url) { 
		String status = "0";
		try {
			String driver = "oracle.jdbc.driver.OracleDriver";
//			  url = "jdbc:oracle:thin:mmmp/mmmp@192.168.21.150:1521:bee";
//						  jdbc:oracle:thin:[username/password]@host_name[:port][:ORCL]
			Class.forName(driver);
			DriverManager.setLoginTimeout(databaseTimeOut);
			Connection con = DriverManager.getConnection(url);
//			System.out.println("测试连接成功");
			status="1";
			con.close(); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return status; 
	}
	public static String CheckAppControl(String url) {
		String status = "0";
		String mess = MyHttpClient.getGetResponseWithHttpClient(url, "utf-8");
		if (mess.trim().length() > 0) {
			status = "1";
		}
		return status;
	}
	
	
	/**
	 * 
	 * <p>Description: http+json request 按流发送 </p>
	 * 极光接口使用
	 * @param url
	 * @param encode
	 * @param requestBody  请求的xml内容
	 * @throws Exception
	 * @return String  
	 * @exception
	 */
	public static String getJpushPostResponseWithHttpClient(String url, String encode, String requestBody, String authorization) throws Exception {
		HttpClient client = new HttpClient(manager);
		if (initialed) {
			MyHttpClient.SetPara();
		}
		PostMethod post = new PostMethod(url);
        post.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, "utf-8");
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        

        ByteArrayRequestEntity entity = new ByteArrayRequestEntity(requestBody.getBytes("utf-8"));
        
        InputStream is = null;

		post.setRequestEntity(entity);
		post.setFollowRedirects(false);
		
		post.setRequestHeader("Content-Type", "text/json;charset=utf-8");
		//	System.out.println("发送XML文件请求长度：===========："+String.valueOf(entity.getContentLength()));
		post.setRequestHeader("Content-Length", String.valueOf(entity.getContentLength()));
		
		
		post.setRequestHeader("Authorization", "Basic " + authorization);
		
		
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			client.executeMethod(post);
			BufferedReader in = new BufferedReader(new InputStreamReader(post
					.getResponseBodyAsStream(), post.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			// iso-8859-1 is the default reading encode
			result = MyHttpClient.ConverterStringCode(resultBuffer.toString(),
					post.getResponseCharSet(), encode);
		} catch (Exception e) {
			// e.printStackTrace();
			result = "";
		} finally {
			post.releaseConnection();
		}
		return result;
	}	
	
	
	public static class CustomFilePart extends FilePart {  
		
		public CustomFilePart(String filename, File file) throws FileNotFoundException {  
			super(filename, file);  
		}  
		
	    protected void sendDispositionHeader(OutputStream out) throws IOException {  
	        super.sendDispositionHeader(out);  
	        String filename = getSource().getFileName();  
	        if (filename != null) {  
	            out.write(EncodingUtil.getAsciiBytes(FILE_NAME));  
	            out.write(QUOTE_BYTES);  
	            out.write(EncodingUtil.getBytes(filename, "utf-8"));  
	            out.write(QUOTE_BYTES);  
	        }  
	    }
	}  
	/**
	 * HTTP post方式调用远程函数 参数设定到body体重
	 * @param postUrl 转码器地址
	 * @param timeout 超时时间
	 * @param requestBody 参数
	 * @return res
	 * @throws Exception
	 */
	public static InputStream getPostResponseWithEntity(String postUrl,int timeout,String requestBody) throws Exception{
		if(postUrl == null || "".equals(postUrl)){
			return null;
		}
		InputStream res = null;									
        PostMethod postMethod = null;
        try {
        	HttpClient client = new HttpClient();   
        	client.setConnectionTimeout(timeout);
        	postMethod = new PostMethod(postUrl);   
        	postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
        	 
        	RequestEntity entity = new StringRequestEntity(requestBody, "text/xml","iso-8859-1");  
    
        	postMethod.setRequestEntity(entity); 

        	int status = client.executeMethod(postMethod);
        	
            if(status==HttpStatus.SC_OK) {
            	
            	logger.info("Response ===>" + postMethod.getResponseBodyAsString());
            	
            	res  = postMethod.getResponseBodyAsStream();
            	
        	}else{
        		throw new Exception("ResponseCode is not 200");
        	}
        } catch (Exception e) {
            e.printStackTrace();
            throw e;

        } finally {
            try {
            	postMethod.releaseConnection();
            } catch (Exception e) {
            }
        }

        return res;
	}	

}
